//开发环境的插件electron
import type { Plugin } from 'vite'
import type { AddressInfo } from 'net'
import { spawn } from 'child_process'
import fs from 'node:fs'

//vite插件要求必须到处一个对象对象必须有name属性
//在这个对象有很多钩子
const buildBackground = () => {
    require('esbuild').buildsync({
        entryPoints: ['src/background.ts'],
        bundle: true,
        outfile: 'dist/background.js',
        platform: 'node',
        target: 'node12',
        external: ['electron']
    })
}

export const ElectronDevPlugin = (): Plugin => {
    return {
        name: 'electron-dev',
        configureServer(server) {
            buildBackground()
            require('esbuild').buildSync({
                entryPoints: ['src/background.ts'],
                bundle: true,
                outfile: 'dist/background.js',
                platform: 'node',
                target: 'node12',
                external: 'electron'
            })

            server?.httpServer?.once('listening', () => {
                const addressInfo = server.httpServer?.address() as AddressInfo
                console.log(addressInfo.port)
                const IP = `http://localhost:${addressInfo.port}`
                //第一个参数是electron的入口文件
                //require('electron')返回是一个路径
                //electron 不认识ts文件编译成js文件
                //进程传参发送给electron IP
                //electron 0 dist/background.js1 IP2
                let ElectronProcess = spawn(require('electron'), ['dist/background.js', IP])
                // 热更新
                fs.watchFile('src/background.ts', () => {
                    ElectronProcess.kill()
                    buildBackground();
                })
                ElectronProcess.stderr.on('data', (data) => {
                    console.log('日志', data.toString())
                })



            })
        }
    }
}